import { useModel, history } from 'umi';
import ConfirmModal from '@/components/ConfirmModal';
import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { Auths, Role } from '@/utils/types.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, message, Modal, notification, Space, Table, Tag } from 'antd';
import { deleteMulLot, queryChargeRules, queryParkinglots, removeParkinglot } from './service';
import type { ParkinglotTableListItem } from './types.d';
import CreateParkinglot from './components/CreateParkinglot';
import UpdateParkinglot from './components/UpdateParkinglot';
import { queryCompanies } from '@/pages/SystemUser/service';
import ExportModal from './components/ExportModal';
import { useRef } from 'react';
import UpdateMulChargeRule from './components/UpdateMulChargeRule';
import { ExclamationCircleOutlined } from '@ant-design/icons';

export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.parkinglot || []) : new Set();
  const ifCreate = auths.has(Auths.CREATE);
  const ifModify = auths.has(Auths.MODIFY);
  const ifDelete = auths.has(Auths.DELETE);
  const ifExport = auths.has(Auths.EXPORT);
  const batchTaskAuth = currUser?.auth ? new Set(currUser.auth.batchTask || []) : new Set();
  const ref = useRef<ActionType>();
  const readBatchTask = batchTaskAuth.has(Auths.READ);
  const headerSubTietleContent = (
    <span>
      一个路段绑定一个巡检车，录入泊位前需要您在此处添加路段，如需批量添加路段信息，请前往
      {readBatchTask ? (
        <a
          onClick={() => {
            history.push('/batch-task');
          }}
        >
          批量任务
        </a>
      ) : (
        '批量任务'
      )}
    </span>
  );
  const columns: ProColumns<ParkinglotTableListItem>[] = [
    {
      title: 'id',
      hideInTable: true,
      hideInSearch: true,
      dataIndex: 'id',
    },
    {
      title: '所属用户',
      dataIndex: 'ownerId',
      hideInForm: true,
      hideInTable: currUser?.role !== Role.ADMIN,
      hideInSearch: currUser?.role !== Role.ADMIN,
      fieldProps: { showSearch: true },
      render: (_, record) => record.ownerInfo?.ownerName,
      debounceTime: 300,
      request: (val) => queryCompanies(val.keyWords),
      width: 150,
    },
    {
      title: '路段名称',
      dataIndex: 'parkingLotName',
      align: 'center',
      ellipsis: true,
      width: 180,
      /* render: (_, record) => (
        <SpotsMarkerModal
          location={record.location}
          parkingLotId={record.parkingLotId}
          parkingLotName={record.parkingLotName}
        />
      ), */
    },
    {
      title: '路段编号',
      dataIndex: 'parkingLotId',
      ellipsis: true,
      width: 300,
    },
    {
      title: '泊位数量',
      dataIndex: 'spotCount',
      align: 'center',
      width: 100,
      hideInSearch: true,
      render: (_, record) => (
        <div
          style={{
            margin: '0 auto',
            minWidth: '60px',
          }}
        >
          {record.spotCount}
        </div>
      ),
    },
    {
      title: '收费规则',
      dataIndex: 'chargeRule',
      align: 'center',
      width: 120,
      fieldProps: { showSearch: true },
      render: (_, record) => record.ruleInfo?.name || '暂无数据',
      debounceTime: 300,
      request: (val) => queryChargeRules(val.keyWords),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
      width: 220,
      hideInSearch: true,
      valueType: 'dateTime',
    },
    {
      title: '所在省市',
      dataIndex: 'province',
      width: 180,
      hideInSearch: true,
      render: (_, record) => <Tag>{record.province.join('')}</Tag>,
    },
    {
      title: '路段位置',
      dataIndex: 'address',
      width: 180,
      hideInSearch: true,
    },
    {
      title: '坐标',
      width: 200,
      dataIndex: 'location',
      hideInSearch: true,
      render: (_, record) => {
        const longtiude = `${record.location[0]}`;
        const latitude = `${record.location[1]}`;
        return `${longtiude.slice(0, 12)}/${latitude.slice(0, 12)}`;
      },
    },
    {
      title: '操作',
      align: 'center',
      width: 150,
      fixed: 'right',
      valueType: 'option',
      render: (_, record, x, action) =>
        ifModify || ifDelete
          ? [
              ifModify && (
                <UpdateParkinglot parkinglotData={record} func={() => action?.reload()} />
              ),
              ifDelete && (
                <ConfirmModal
                  reload={() => action?.reload()}
                  operFunc={async () => await removeParkinglot(record._id)}
                  danger
                  text={
                    <span>
                      正在删除{record.parkingLotName}，该操作会一并
                      <b style={{ color: 'red' }}>删除此路段下所有泊位数据</b>
                      ，并且可能会造成该路段下的<b style={{ color: 'red' }}>会员信息</b>及
                      <b style={{ color: 'red' }}>尚未驶出的订单</b>
                      异常。如有需要，请提前做好数据备份。
                      <span style={{ color: '#7bb2df', fontWeight: 'bold' }}>
                        如需结束该路段下当前在停所有订单，请联系管理员前往批量任务进行操作
                      </span>
                    </span>
                  }
                />
              ),
            ]
          : [<PlaceHolderCpn key={record._id} />],
    },
  ];
  const openNotification = (msg: string = '删除失败') => {
    const key = `open${Date.now()}`;
    const btn = (
      <Button type="primary" size="small" onClick={() => notification.close(key)}>
        已读
      </Button>
    );
    notification.open({
      message: '路段批量删除失败',
      description: msg,
      btn: btn,
      duration: null,
      key,
    });
  };
  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: headerSubTietleContent,
        breadcrumb: {
          routes: [
            { path: '/', breadcrumbName: '首页' },
            { path: '/parking', breadcrumbName: '停车管理' },
            { path: '/parking/parkinglot', breadcrumbName: '路段管理' },
          ],
        },
      }}
    >
      <ProTable<ParkinglotTableListItem>
        rowKey="parkingLotId"
        columns={columns}
        search={{ labelWidth: 'auto' }}
        scroll={{ x: true }}
        style={{ whiteSpace: 'nowrap' }}
        columnEmptyText="暂无数据"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
          onChange: () => {
            if (ref?.current?.clearSelected) ref?.current?.clearSelected();
          },
        }}
        debounceTime={300}
        request={async (param, sort) => {
          const res = await queryParkinglots(param, sort);
          return res;
        }}
        rowSelection={{
          selections: [Table.SELECTION_ALL],
        }}
        actionRef={ref}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <span>
            已选 {selectedRowKeys.length} 项
            <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
          </span>
        )}
        tableAlertOptionRender={({ selectedRowKeys }) => {
          return ifModify || ifDelete ? (
            <Space size={16}>
              {ifDelete && (
                <a
                  onClick={async () => {
                    if (selectedRowKeys.length <= 0) {
                      message.warn({
                        content: '请选择要删除的路段',
                        key: 'mul-lot',
                      });
                      return false;
                    }
                    Modal.error({
                      title: '删除确认',
                      icon: <ExclamationCircleOutlined />,
                      width: '40vw',
                      content: (
                        <span>
                          是否确认删除当前所选项，此操作将
                          <b style={{ color: 'red' }}>同步删除对应路段下所有泊位</b>
                          ，并且可能会造成相关路段下的<b style={{ color: 'red' }}>会员信息</b>及
                          <b style={{ color: 'red' }}>尚未驶出的订单</b>异常。
                          <span style={{ color: '#7bb2df', fontWeight: 'bold' }}>
                            如需结束该路段下当前在停所有订单，请联系管理员前往批量任务进行操作
                          </span>
                        </span>
                      ),
                      okButtonProps: {
                        danger: true,
                      },
                      okCancel: true,
                      onOk: async () => {
                        message.loading({ content: '正在删除...', key: 'mul-lot' });
                        const res = await deleteMulLot(selectedRowKeys as string[]);
                        ref.current?.reload();
                        if (res?.success) {
                          message.success({ content: '删除成功', key: 'mul-lot' });
                          return true;
                        }
                        openNotification(res?.message);
                        return false;
                      },
                    });
                    return false;
                  }}
                >
                  批量删除
                </a>
              )}
              {ifModify && (
                <UpdateMulChargeRule
                  realod={() => {
                    ref.current?.reload();
                    if (ref?.current?.clearSelected) ref.current?.clearSelected();
                  }}
                  parkingLotIds={selectedRowKeys as string[]}
                />
              )}
            </Space>
          ) : (
            <PlaceHolderCpn />
          );
        }}
        toolBarRender={(action) => [
          ifCreate && <CreateParkinglot func={() => action?.reload()} />,
          ifExport && <ExportModal />,
        ]}
      />
    </PageHeaderWrapper>
  );
};
